#!/usr/bin/python
# -*- coding: utf-8 -*-
import xlrd
import json
import lxml.etree as et
from xlrd.sheet import Sheet


# 获取配置文件
def get_config():
    try:
        config_file = open('config.json', 'r', encoding='UTF-8')
    except FileNotFoundError:
        print('未找到配置文件config.json,请确保和脚本文件放置在同一目录下')
        exit()
    json_config = json.loads(config_file.read())
    config_file.close()
    return json_config


# 获取excel对应sheet的表格
def get_excel_table(file_name, sheet_name):
    try:
        data = xlrd.open_workbook(file_name)
    except FileNotFoundError:
        print('未找到excel表格，请确保config.json中配置的文件路径')
        exit()
    try:
        sheet = data.sheet_by_name(sheet_name)
    except xlrd.biffh.XLRDError as e:
        print(e)
        exit()
    return sheet


# 获取string资源文件字典
def get_xml_files(config):
    files = {}
    language_map = config['language_map']
    for language_name in language_map:
        language_folder = language_map[language_name]
        # print(language_map[language_name])
        if isinstance(language_folder, list):
            folders = []
            for folder in language_folder:
                folders.append(config['project_res_path'] + folder + '\\' + config['project_res_file_name'])
            files[language_name] = folders
        else:
            files[language_name] = config['project_res_path'] + language_folder + '\\' + config['project_res_file_name']
    return files


# 添加注释
def add_comment(comment, files):
    for language in files:
        file = files[language]
        if isinstance(file, list):
            for f in file:
                add_comment_to_file(comment, f)
        else:
            add_comment_to_file(comment, file)


def add_comment_to_file(comment, file_name):
    comment = comment.strip()

    parser = et.XMLParser(strip_cdata=False)
    with open(file_name, "rb") as source:
        tree = et.parse(source, parser=parser)

    root = tree.getroot()
    root[-1].tail = '\n\n    '

    if not comment:
        tree.write(file_name, pretty_print=True, encoding='UTF-8', xml_declaration=True)
        return

    comment = et.Comment(comment)
    comment.tail = '\n    '
    root.append(comment)
    tree.write(file_name, pretty_print=True, encoding='UTF-8', xml_declaration=True)


# 添加翻译
def add_translation(table: Sheet, files):
    if table.nrows <= 1:
        raise Exception('excel表行数至少为2行！')
    elif table.ncols <= 1:
        raise Exception('excel表列数至少为2行！')
    else:
        language_names = table.row_values(0)
        add_comment(language_names[0], files)
        for i in range(1, table.nrows):
            row = table.row_values(i)
            for j in range(1, table.ncols):
                language_file = get_language_file(language_names[j], files)
                if isinstance(language_file, list):
                    for file in language_file:
                        add_translation_to_file(row[j], row[0], file)
                elif language_file is not None:
                    add_translation_to_file(row[j], row[0], language_file)


def add_translation_to_file(word, string_id, file_name):
    word = word.strip()
    if not word:
        return
    # 处理特殊字符
    word = word.replace('\'', '\\\'')
    word = word.replace('&', '\\&')
    parser = et.XMLParser(strip_cdata=False)
    with open(file_name, "rb") as source:
        tree = et.parse(source, parser=parser)
    is_exist = False
    for child_root in tree.getroot().iter(tag='string'):
        if child_root.attrib['name'] == string_id:
            child_root.text = word
            is_exist = True
            break

    root = tree.getroot()
    if not is_exist:
        last_node = root[-1]
        if last_node.tail != '\n\n    ':
            root[-1].tail = '\n    '

        node = et.Element('string', {'name': string_id})
        node.text = word
        node.tail = '\n'
        root.append(node)
    else:
        root[-1].tail = '\n'

    tree.write(file_name, pretty_print=True, encoding='UTF-8', xml_declaration=True)


# 遍历字典，获取对应语言文件或文件集
def get_language_file(language_name, files):
    for language in files:
        if language in language_name:
            return files[language]


def run():
    json_config = get_config()
    table = get_excel_table(json_config['excel_file_path'], json_config['excel_sheet_name'])
    files = get_xml_files(json_config)
    add_translation(table, files)
    print('导入成功')


run()
